<?php

namespace App\Exceptions;

use App\Enums\HttpCode;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     * dontReport
     * @return void
     */
    public function register()
    {
        $this->reportable(function (RJsonError $e) {
            $log = 'URL:' . request()->url() . "        File:" . $e->getFile() . "        LINE:" . $e->getLine() . "        MESSAGE:" . $e->getMessage();
            $filePath = storage_path('logs/' . date('Y') . '/' . date('m') . '/' . date('d'));
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            file_put_contents($filePath . '/' . date('Y-m-d') . '_laravel.log', '[' . date('Y-m-d H:i:s') . '] ' . $log . "\r\n", FILE_APPEND);
        })->stop();
    }

    public function render($request, Throwable $e)
    {
        if ($e instanceof MethodNotAllowedHttpException || $e instanceof NotFoundHttpException) {
            return response()->json([
                'message' => "请求不存在！",
                'statusCode' => HttpCode::NOT_FOUND
            ]);
        }

        if (request()->segment(1) == 'api') {
            if ($e instanceof UnauthorizedHttpException) {
                return response()->json([
                    'statusCode' => HttpCode::UNAUTHORIZED,
                    'message' => '登陆已过期，请重新登陆'
                ]);
            }
        }

        if ($e instanceof \Exception) {
            return response()->json([
                'message' => $e->getMessage(),
                'statusCode' => HttpCode::BAD_REQUEST
            ]);
        }
        return parent::render($request, $e);
    }
}
